// pages/exercise/exercise.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';

const app = getApp()
var correctNum = 0;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    dataOK: false, //数据准备好了
    grade: 0,  //选择的年级
    num: 5,   //题目总数
    cur: 0,   //当前是第几题 cur: [0, num)
    typeInfo: [
      {
        label: '未分类',
        eg: '暂无'
      },
      {
        label: '整数加减法',
        eg: '16 + 28 = 44'
      },
      {
        label: '整数乘除法',
        eg: '22 × 2 = 11'
      },
      {
        label: '小数加减法',
        eg: '1.6 + 0.4 = 2.0'
      },
      {
        label: '小数乘除法',
        eg: '1.2 ÷ 2.0 = 0.6'
      },
      {
        label: '小数比大小',
        eg: '1.56 < 1.7'
      },
      {
        label: '分数加减法',
        eg: '1/2 - 1/3 = 1/6'
      },
      {
        label: '分数乘除法',
        eg: '1/3 ÷ 1/2 = 2/3'
      },
      {
        label: '分数比大小',
        eg: '1/3 < 1/2'
      },
      {
        label: '四则运算',
        eg: '1+2*3=7'
      },
    ],
    radio: ['0'],   //单选框选项
    r: ['⚪', '<', '>', '='],
    ansIn: [''], //用户输入
    validate: [false], //是否校检答案
    correct: [true], //是否正确
    collect: [false],  //题目是否被收藏
    barColor: [''], //进度条颜色，代表题目是否做对
    problems: []  //问题数组（由ks-api得来）
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    correctNum = 0;
    this.setData({
      grade: app.globalData.grade,
      num: parseInt(options.num),
      cur: 0,
      dataOK: false
    })
    //请求题目
    this.getExercises(this.data.num);
    //初始化
    for (let i = 0; i < this.data.num; i++) {
      this.setData({
        [`ansIn[${i}]`]: '',
        [`radio[${i}]`]: '0',
        [`validate[${i}]`]: false,
        [`correct[${i}]`]: true,
        [`collect[${i}]`]: false,
        [`barColor[${i}]`]: '#7232dd',
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   * 要将所有收藏上传服务端
   */
  onUnload: function () {
    var collections = {
      env: 'exercise',
      openid: app.globalData.openid,
      ord4cancel: [],
      num: 0,
      details: []
    }
    for (let i = 0; i < this.data.num; i++) {
      if (this.data.collect[i]) {
        let prob = this.data.problems[i];
        prob.opt_usr = parseInt(this.data.radio[i]);
        prob.ans_usr = this.data.ansIn[i];
        collections.details.push(prob);
        collections.num++;
      }
    }
    if (collections.num == 0) {
      return;
    }
    //调用ks-api收藏题目
    wx.cloud.callContainer({
      config: {
        env: "prod-6gmuxgtca5913e7c"
      },
      path: "/collections",
      header: {
        'X-WX-SERVICE': "ks-api",
        'content-type': "application/json"
      },
      method: "POST",
      data: collections,
      success: function (res) {
        Notify({
          type: 'success',
          message: '收藏上传成功！'
        })
      },
      failed: function (res) {
        Notify({
          type: 'danger',
          message: '收藏上传失败。'
        })
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 复选框逻辑
   */
  onChangeRadio(event) {
    this.setData({
      [`radio[${this.data.cur}]`]: event.detail,
    });
  },

  onClickRadio(event) {
    if (this.data.validate[this.data.cur]) { return; }
    const { name } = event.currentTarget.dataset;
    this.setData({
      [`radio[${this.data.cur}]`]: name,
    });
  },

  /**
   * 用户点击检查，检查答案是否正确并显示正确答案
   */
  onValidate() {
    let cur = this.data.cur;
    let problem = this.data.problems[cur];
    this.setData({
      [`validate[${cur}]`]: true,
    })  //切换检查态
    if (problem.type == 5 || problem.type == 8) {
      //检查选择题
      let opt_usr = parseInt(this.data.radio[cur]);
      this.setData({
        [`ansIn[${cur}]`]: problem.formula.replace('⚪', this.data.r[opt_usr]),
        [`correct[${cur}]`]: ((opt_usr == problem.option) ? true : false)
      })
    } else {
      this.setData({
        [`correct[${cur}]`]: ((this.data.ansIn[cur] == problem.answer) ? true : false)
      })
    }
    //提示消息
    if (this.data.correct[cur]) {
      correctNum++;
      Notify({ type: "success", message: "恭喜，答案正确！", duration: 1000 })
    } else {
      Notify({ type: "danger", message: "很遗憾，没能做对。", duration: 1000 })
    }
    this.setData({ [`barColor[${cur}]`]: this.data.correct[cur] ? '#07c160' : '#ee0a24' }) //显示批改标签
  },

  /**
   * 用户点击“下一题”，加载下一题
   */
  onNext(event) {
    let that = this;
    if (this.data.cur + 1 == this.data.num) {
      //最后一道题
      Dialog.confirm({
        title: '- 提示 -',
        message: `共做对了 ${correctNum} 题，是否退出练习？`,
      })
        .then(() => {
          // on confirm 回退一个页面
          wx.navigateBack({
            delta: 1,
          })
        })
        .catch(() => {
          // on cancel 什么也不做
        });
    } else {
      this.setData({
        cur: that.data.cur + 1
      })
    }
  },

  /**
   * 用户点击上一题，加载上一题
   */
  onPrev(event) {
    this.setData({
      cur: this.data.cur - 1
    })
  },

  /**
   * 获取练习习题
   */
  getExercises(num) {
    let that = this
    //调用ks-api接口取得题目
    wx.cloud.callContainer({
      config: {
        env: "prod-6gmuxgtca5913e7c"
      },
      path: "/problems",
      header: {
        'X-WX-SERVICE': "ks-api",
        'content-type': "application/json"
      },
      method: "GET",
      data: {
        env: 'exercise',
        grade: this.data.grade,
        num: num
      },
      success: function (res) {
        if (res.statusCode != 200) {
          Dialog.confirm({
            title: '加载失败',
            message: '题目不翼而飞了呢，请检查网络连接。',
          })
            .then(() => {
              // on confirm
              wx.navigateBack({
                delta: 1,
              })
            })
        } else {
          that.setData({
            [`problems`]: res.data.details,
            dataOK: true
          })
        }
      },
      failed: function (res) {
        Dialog.confirm({
          title: '加载失败',
          message: '题目不翼而飞了呢，请检查网络连接。',
        })
          .then(() => {
            // on confirm
            wx.navigateBack({
              delta: 1,
            })
          })
      }
    })
  },

  /**
   * 输入答案触发，更新this.data.ansIn
   */
  onInput(event) {
    let cur = this.data.cur
    this.setData({
      [`ansIn[${this.data.cur}]`]: event.detail
    })
  },

  /**
   * 用户收藏题目
   */
  onCollect() {
    let isCollected = this.data.collect[this.data.cur]
    if (isCollected) {
      Notify({
        background: '#FFFFFF',
        color: '#000000',
        message: '取消收藏 ×',
        duration: 1000
      })
    } else {
      Notify({
        background: '#fffe02',
        color: '#000000',
        message: '收藏成功 √',
        duration: 1000
      })
    }
    this.setData({
      [`collect[${this.data.cur}]`]: !isCollected
    })
  }
})